
<template>
    <base-node type="ai_intention" :config="props.data" :id="props.id" ref="baseNode">
        <template #default>
            <label>问题</label>
            <n-select placeholder="请选择问题" clearable v-model:value="props.data.intentionConfig.inputField"
                      :options="prevOutputFieldOptions"></n-select>
            <!-- 意图数组 -->
            <label>意图</label>
            <div v-for="(intention, index) in props.data.intentionConfig.intentions" :key="intention.id"
                 class="intention-item flex justify-between items-end">
                <div class="flex-col items-start flex-1 overflow-hidden">
                    <n-popover trigger="hover" style="max-width: 200px;">
                        <template #trigger>
                            <div class="ellipsis max-w-full cursor-pointer">
                                <b class="mr-2">{{ intention.key }}</b>
                                {{ intention.description }}
                            </div>
                        </template>
                        <span>{{ intention.description }}</span>
                    </n-popover>
                    <n-popover trigger="hover" style="max-width: 200px">
                        <template #trigger>
                            <div class="ellipsis  max-w-full  cursor-pointer text-gray-500">
                                {{ intention.cases.join('; ') }}
                            </div>
                        </template>
                        <span>{{ intention.cases.join('; ') }}</span>
                    </n-popover>
                </div>
                <div class="shrink-0 ml-4">
                    <jb-btn text size="small" drawerTitle="编辑意图" icon=" " type="primary" ghost
                            :drawerComponent="IntentionEditDrawer" :drawerComponentProps="{show:showEditDrawer,data: props.data,
                intention: props.data.intentionConfig.intentions[index],
                index: index}" :drawerArgs="{width: '500px',maskClosable:false}" @drawerYesClick="handleDrawerUpdateYesClick">
                        <jb-icon icon="ant-design:edit-filled" :local="true"></jb-icon>
                    </jb-btn>&nbsp;
                    <jb-btn text strong ghost type="error" size="small" icon="ri:delete-bin-line"
                            @click="removeIntention(index)">
                    </jb-btn>

                </div>


            </div>

            <div key="INNER_NO_MATCH" class="intention-item no-match flex justify-center items-center">
                <b class="text-gray-500">未匹配任何意图</b>
            </div>
            <div class="w-full">
                <jb-btn style="width: 470px;" drawerTitle="添加意图" type="success" :drawerComponent="IntentionEditDrawer"
                        :drawerComponentProps="{show:showEditDrawer,data: props.data,
                    intention: emptyIntention,index: 0}" :drawerArgs="{width: '500px',maskClosable:false}"
                        @drawerYesClick="handleDrawerAddYesClick"> 添加意图
                </jb-btn>
            </div>
            <label>AI 模型</label>
            <jb-select url="aiResource/listAllEnabledType" labelField="name" placeholder="请选择AI模型" valueField="sn"
                       v-model:value="props.data.llmConfig.modelType"></jb-select>

        </template>
        <template #source>
            <Handle type="source" id="fail" :position="Position.Right"
                    style="top: 140px"/>
            <template v-for="(item,index) in props.data.intentionConfig.intentions" :key="item.id">
                <Handle type="source" :id="item.key" :position="Position.Right" :style="{top: `${230 + 68*index}px`}" class="intention"/>
            </template>

            <Handle type="source" id="INNER_NO_MATCH" class="intention"
                    :position="Position.Right" style="top:initial;bottom: 265px;"/>
        </template>

        <template #footer>
            <p class="tc-gray ">输出字段</p>
            <div class="output mt-8 pad-8 fx fx-c_center fx-m_between">
                <div class="fx fx-c_center">
                    <div class="output-flag noshrink"></div>
                    <n-input v-model:value="props.data.intentionConfig.outputField" placeholder="字段名"
                             class="tc-gray ml-8 w-120"></n-input>
                </div>
                <span class="tc-assist">AI生成的回答</span>
            </div>
        </template>

    </base-node>
</template>
<script setup>

import {
    Position,
    Handle,
    useNode,
    useVueFlow
} from '@vue-flow/core'
import {
    ref,
    watch,
    onMounted,
    computed,
    onUnmounted,
    inject
} from "vue";
import {
    NInput
} from 'naive-ui';
import {
    useMessage
} from "naive-ui";
import {
    getNodeOutputFieldNames
} from '../node-def'
import BaseNode from '@/views/app/chain/nodes/BaseNode.vue'
import IntentionEditDrawer from './cnps/IntentionEditDrawer.vue';

const message = useMessage();
const props = defineProps(['id', 'data'])

const flow = useVueFlow();
const showEditDrawer = ref(false);
//空的意图对象
const emptyIntention = {
    key: "",
    description: "",
    cases: ['']
};

const baseNode = ref(null);

/** 获取所有前置节点的输出字段，并生成下拉选项 */
const prevOutputFieldOptions = computed(() => {
    return baseNode.value ? baseNode.value.prevOutputFieldOptions : [];
});


//监听prevOutputFieldOptions
watch(() => prevOutputFieldOptions.value, (newV, oldV) => {
    //初始化之后，如果数组某次是空值,则清空input的值
    if (baseNode.value?.initDone && newV && !newV.find(v => v.value == props.data.intentionConfig.inputField)) {
        // inputField.value = null;
        props.data.intentionConfig.inputField = null;
    }
})


// 关闭抽屉--添加意图
function handleDrawerAddYesClick({
                                     componentRef,
                                     close
                                 }) {
    componentRef.submit((data) => {
        //判断 data中的key跟描述不能为空值
        if (!validateData(data)) {
            return;
        }
        //检查key值是否重复
        const intentions = props.data.intentionConfig.intentions;
        // 检查除当前意图外是否有重复的key
        for (let i = 0; i < intentions.length; i++) {
            if (intentions[i].key === data.value.key.trim()) {
                message.error('该 Key 已存在，请使用其他 Key');
                return;
            }
        }
        console.debug("新增意图", data.value)
        props.data.intentionConfig.intentions.push(data.value);
        close();
    })
}

// 关闭编辑抽屉--修改意图
function handleDrawerUpdateYesClick({
                                        componentRef,
                                        close
                                    }) {

    componentRef.submit((data, index) => {
        //判断 data中的key跟描述不能为空值
        if (!validateData(data)) {
            return;
        }
        //检查key值是否重复
        const intentions = props.data.intentionConfig.intentions;
        // 检查除当前意图外是否有重复的key
        for (let i = 0; i < intentions.length; i++) {
            if (i !== index && intentions[i].key === data.value.key.trim()) {
                message.error('该 Key 已存在，请使用其他 Key');
                return;
            }
        }


        console.debug("修改意图", data.value)
        props.data.intentionConfig.intentions[index] = data.value;
        close();
    })
}

//检验值
function validateData(data) {
    // 判断 data中的key跟描述不能为空值
    if (data.value.key.trim() === '') {
        message.error('Key不能为空');
        return false;
    }
    if (data.value.description.trim() === '') {
        message.error('描述不能为空');
        return false;
    }

    // 案例数组中也不能为空
    if (data.value.cases.length === 0) {
        message.error('案例不能为空');
        return false;
    }
    for (let i = 0; i < data.value.cases.length; i++) {
        if (data.value.cases[i].trim() === '') {
            message.error('案例不能为空');
            return false;
        }
    }


    return true;
}




// 删除意图
const removeIntention = (index) => {
    const intention = props.data.intentionConfig.intentions[index];
    //移除连线
    flow.removeEdges((edges) => {
        console.debug("移除意图识别的连线", edges);
        return edges.filter(edge => edge.source == props.id && edge.sourceHandle == intention.key);
    })
    props.data.intentionConfig.intentions.splice(index, 1);


};




</script>


<style scoped>



label {
    margin-bottom: 8px;
}

label:not(:first-child) {
    margin-top: 16px;
}

.output {
    background: rgb(249, 250, 251);
    border-radius: 12px;
}

.output-flag {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: #22c55e;
}


.intention-item {
    background-color: rgba(240, 173, 78, 0.04);
    border: 1px solid rgba(240, 173, 78, 0.16);
    padding: 8px 16px;
    height: 60px;
    box-sizing: border-box;
    margin-bottom: 8px;
    border-radius: 4px;
    position: relative;
}

.intention-item.no-match {
    background-color: rgba(121, 121, 121, 0.05);
}

.no-match :deep(n-empty__description) {
    font-size: 12px;
}



</style>